package com.common.util;

import android.text.TextUtils;
import android.util.Log;

import org.apache.http.params.HttpParams;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {

	public static  final  String TAG = "OkHttpUtil";
	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

	private static OkHttpClient okHttpClient = null;

	private static  final int TIMEOUT = 10000;//请求超时限制,ms

	public static Response executePost(String url,HashMap<String,String> headers, HashMap<String,String> params) {
		try {
			if (TextUtils.isEmpty(url) || !url.startsWith("http")) {
				MyLoger.e(TAG,"executePostParam parameter error url = "+ url);
				return null;
			}

			OkHttpClient client = getOkHttpClient();

			FormBody.Builder builder = new FormBody.Builder();
			if (params != null && !params.isEmpty()) {
				for (Map.Entry<String,String> entry: params.entrySet()) {
					builder.add(entry.getKey(),entry.getValue());
				}
			}

			FormBody formBody =  builder.build();
			Request.Builder requestBuild = new Request.Builder().url(url).post(formBody);
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String,String> entry: headers.entrySet()) {
					requestBuild.addHeader(entry.getKey(),entry.getValue());
				}
			}
			Request request = requestBuild.build();
			Response response = client.newCall(request).execute();

			return response;


		} catch (Exception e) {
			MyLoger.e(TAG,"executePostParam ERROR!!! url = "+url+ "  , catch Exception e = "+ e.getClass().getSimpleName());
			e.printStackTrace();
		}

		return null;
	}
	public static String executePostParam(String url,HashMap<String,String> headers, HashMap<String,String> params) {

		try {
			if (TextUtils.isEmpty(url) || !url.startsWith("http")) {
				MyLoger.e(TAG,"executePostParam parameter error url = "+ url);
				return "";
			}

			OkHttpClient client = getOkHttpClient();

			FormBody.Builder builder = new FormBody.Builder();
			if (params != null && !params.isEmpty()) {
				for (Map.Entry<String,String> entry: params.entrySet()) {
					builder.add(entry.getKey(),entry.getValue());
				}
			}

			FormBody formBody =  builder.build();
			Request.Builder requestBuild = new Request.Builder().url(url).post(formBody);
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String,String> entry: headers.entrySet()) {
					requestBuild.addHeader(entry.getKey(),entry.getValue());
				}
			}
			Request request = requestBuild.build();
			Response response = client.newCall(request).execute();
			String ret = response.body().string();
			return ret;


		} catch (Exception e) {
			MyLoger.e(TAG,"executePostParam ERROR!!! url = "+url+ "  , catch Exception e = "+ e.getClass().getSimpleName());
			e.printStackTrace();
		}

		return null;

	}
	public static String executeGet(String url, HashMap<String,String> headers, HashMap<String,String> params) {

		try {

            MyLoger.d(TAG,"executeGet url = "+url);
			if (TextUtils.isEmpty(url) || !url.startsWith("http")) {
				MyLoger.e(TAG,"executeGet parameter error url = "+ url);
				return "";
			}

			if (params != null && !params.isEmpty()) {
				if (url.contains("?")) {
					url += "&";
				} else {
					url += "?";
				}
				for (Map.Entry<String,String> entry: params.entrySet()) {
					url += entry.getKey() + "=" + entry.getValue()+ "&";
				}
			}
			OkHttpClient client = getOkHttpClient();
			client.sslSocketFactory();

			Request.Builder requestBuild= new Request.Builder().url(url);
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String,String> entry: headers.entrySet()) {
                    MyLoger.d(TAG,"executeGet add header = "+entry.getKey()+" : "+entry.getValue());
					requestBuild.addHeader(entry.getKey(),entry.getValue());
				}
			}
			Request request = requestBuild.build();
			Response response = client.newCall(request).execute();

			String ret = response.body() != null ? response.body().string() : "";

            MyLoger.d(TAG,"executeGet ret = "+ret);

			return ret;


		} catch (Exception e) {
			MyLoger.e(TAG,"executeGet ERROR!!! url = "+url+ "  , catch Exception e = "+ e.getClass().getSimpleName());
			e.printStackTrace();

		}

		return null;

	}

	public static String executePostJson(String url, HashMap<String,String> headers, HashMap<String,String> params,String content) {
		try {
			if (TextUtils.isEmpty(url) || !url.startsWith("http")) {
				MyLoger.e(TAG,"executePostJson parameter error url =  "+ url);
				return "";
			}
			OkHttpClient client = getOkHttpClient();
			FormBody.Builder builder = new FormBody.Builder();
			if (params != null && !params.isEmpty()) {
				for (Map.Entry<String,String> entry: params.entrySet()) {
					builder.add(entry.getKey(),entry.getValue());
				}
			}
			FormBody formBody =  builder.build();
			Request.Builder requestBuild = new Request.Builder().url(url).post(formBody);
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String,String> entry: headers.entrySet()) {
					requestBuild.addHeader(entry.getKey(),entry.getValue());
				}
			}
			RequestBody body = RequestBody.create(JSON, content);
			Request request = requestBuild.post(body).build();
			Response response = client.newCall(request).execute();

			String ret = response.body().string();
			return ret;

		} catch (Exception e) {
			MyLoger.e(TAG,"executePostJson ERROR!!! url = "+url+ "  , catch Exception e = "+ e.getClass().getSimpleName());
			e.printStackTrace();
		}
		return null;

	}

	public static OkHttpClient getOkHttpClient() {

		if(okHttpClient != null){
			return okHttpClient;
		}
		OkHttpClient.Builder builder = new OkHttpClient.Builder()
				//.retryOnConnectionFailure(true)
				.connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
				.readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
				.hostnameVerifier(new HostnameVerifier() {
					@Override
					public boolean verify(String hostname, SSLSession session) {
						return true;
					}
				});

		if (true) {//2种可使用SSL的方式，这种不行用else的
			SSLUtils.SSLParams sslParams = SSLUtils.getSslSocketFactory(null, null, null);
			builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
		} else {

			SSLContext sslContext = null;
			try {
				sslContext = SSLContext.getInstance("TLS");
				try {
					sslContext.init(null, null, null);
				} catch (KeyManagementException e) {
					e.printStackTrace();
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}

			SSLSocketFactory socketFactory = new Tls12SocketFactory(sslContext.getSocketFactory());
			builder.sslSocketFactory(socketFactory, new SSLUtils.UnSafeTrustManager());
		}

		okHttpClient =  builder.build();
		return okHttpClient;
	}

}

